const https = require("https");
const querystring = require("querystring");
const url = require("url");
//const port = 10101;
//// 1.创建代理服务
//https.createServer(onRequest).listen(port);
//
//console.log('------',https)
//
//function onRequest(req, res) {
//	console.log(req,res);
//	const originUrl = url.parse(req.url);
//	const qs = querystring.parse(originUrl.query);
//	const targetUrl = qs["target"];
//	const target = url.parse(targetUrl);
//	const options = {
//		hostname: target.hostname,
//		port: 80,
//		path: url.format(target),
//		method: "GET"
//	};
//	// 2.代发请求
//	const proxy = https.request(options, _res => {
//		// 3.修改响应头
//		const fieldsToRemove = ["x-frame-options", "content-security-policy"];
//		Object.keys(_res.headers).forEach(field => {
//			if (!fieldsToRemove.includes(field.toLocaleLowerCase())) {
//				res.setHeader(field, _res.headers[field]);
//			}
//		});
//		_res.pipe(res, {
//			end: true
//		});
//	});
//	req.pipe(proxy, {
//		end: true
//	});
//}
var express = require("express");
var bodyParser     =   require("body-parser"); 
var app = express(); 
app.use(bodyParser.urlencoded({ extended: false }));  
var hostName = '127.0.0.1';
var port = 10101;

app.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
    next();  
});

app.get("/get",function(req,res){
	const originUrl = url.parse(req.url);
	const qs = querystring.parse(originUrl.query);
	const targetUrl = qs["target"];
	const target = url.parse(targetUrl);
	const options = {
		hostname: target.hostname,
		port: 80,
		path: url.format(target),
		method: "GET"
	};
	
	const proxy = https.request(options, _res => {
		// 3.修改响应头
		const fieldsToRemove = ["x-frame-options", "content-security-policy"];
		Object.keys(_res.headers).forEach(field => {
			if (!fieldsToRemove.includes(field.toLocaleLowerCase())) {
				res.setHeader(field, _res.headers[field]);
			}
		});
		_res.pipe(res, {
			end: true
		});
	});
	req.pipe(proxy, {
		end: true
	});
	
	console.log("请求url：",req.path)
    console.log("请求参数：",req.query)
    
    
    
    res.send('https%3A%2F%2Fgithub.com%2Fjoin');
})

app.post("/post",function(req,res){
    console.log("请求参数：",req.body);
    var result = {code:200,msg:"post请求成功"};
    res.send(result);
});


app.listen(port,hostName,function(){

   console.log(`服务器运行在http://${hostName}:${port}`);

});